﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace PowerTriggersWcf
{
    internal static class EventLogHelper
    {
        private const string ApplicationEventSource = "PowerTriggersService";

        public static void LogInformation(string message)
        {
            LogEntry(message, EventLogEntryType.Information);
        }

        public static void LogWarning(string message)
        {
            LogEntry(message, EventLogEntryType.Warning);
        }

        public static void LogError(string message)
        {
            LogEntry(message, EventLogEntryType.Error);
        }

        public static void LogError(string message, System.Exception ex)
        {
            try
            {
                if (ex == null)
                {
                    message = message.Trim() + ": Unknown error";
                }
                else
                {
                    message = message.Trim() + ": " + ex.Message.Trim();
                    var outer = ex;
                    while (outer.InnerException != null)
                    {
                        if (outer.InnerException.Message.Trim() != outer.Message.Trim())
                        {
                            message += ", " + outer.InnerException.Message.Trim();
                        }
                        outer = outer.InnerException;
                    }
                }
            }
            catch { }

            LogEntry(message, EventLogEntryType.Error);
        }

        private static void LogEntry(string message, EventLogEntryType logType)
        {
            try
            {
                if (!EventLog.SourceExists(ApplicationEventSource))
                    EventLog.CreateEventSource(ApplicationEventSource, "Application");

                using (EventLog ncsLog = new EventLog())
                {
                    ncsLog.Source = ApplicationEventSource;
                    ncsLog.WriteEntry(message.Trim(), logType);
                }
            }
            catch { }
        }
    }
}
